import categoryData from "./categoryData";
import Vue from "vue"
import {isEmpty} from "../../../js/commonUtils";

export const queryCategories = (self, expandIds) => {
  self.$Spin.show();
  self.$apiImpProduct.queryAllCategories().then(response => {
    self.$Spin.hide();
    categoryData.tData.categoryTreeData.splice(0);
    if(response.success) {
      let result = response.result;
      let treeData = makeCategoryTree(result, expandIds);
      categoryData.tData.categoryTreeData.push(...treeData);
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}

const makeCategoryTree = (categoryList, expandIds) => {
  let catsLevel1 = [];
  let catsLevel2 = [];
  let catsLevel3 = [];
  //分类分组
  for(let cat of categoryList) {
    if(expandIds!=null && expandIds.length>0 && expandIds.indexOf(cat.id)>=0) {
      cat._showChildren = true;
      // Vue.set(cat, "_expanded", true);
    }
    switch(cat.level) {
      case 1:
        cat.children = [];
        catsLevel1.push(cat);
        break;
      case 2:
        cat.children = [];
        catsLevel2.push(cat);
        break;
      case 3:
        catsLevel3.push(cat);
        break;
    }
  }
  //构建分类树形json
  //2，3级分类
  for(let cat2 of catsLevel2) {
    for(let cat3 of catsLevel3) {
      if(cat3.parentId == cat2.id) {
        cat2.children.push(cat3);
      }
    }
  }
  //1,2级分类
  for(let cat1 of catsLevel1) {
    for(let cat2 of catsLevel2) {
      if(cat2.parentId == cat1.id) {
        cat1.children.push(cat2);
      }
    }
  }
  return catsLevel1;
}

export const addOrUpdateCategory = (self) => {
  if(isEmpty(categoryData.tParam.paramCategory.name)) {
    self.$Message.error("分类名称不能为空！");
    return;
  }
  let params = {category: categoryData.tParam.paramCategory};
  self.$Spin.show();
  self.$apiImpProduct.addOrUpdateCategory(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      categoryData.tStatus.paramCategoryModal.isShow = false;
      queryCategories(self, params.category.ancestorIds);
    }else{
      self.$Message.error(response.errorMessage);
    }
  })
}

export const deleteCategory = (self, category) => {
  let params = {id: category.id};
  self.$Spin.show();
  self.$apiImpProduct.deleteCategory(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      queryCategories(self, category.ancestorIds);
    }else{
      self.$Message.error(response.errorMessage);
    }
  });
}
